package com.androidhive.androidlistview;

import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.webkit.WebView;
import android.widget.HorizontalScrollView;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableLayout.LayoutParams;
import android.widget.TableRow;
import android.widget.TextView;

public class CropTable extends Activity {
	SessionManager session;
	 private WebView webView1,webView2;

	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    session = new SessionManager(getApplicationContext());
	   // setContentView(R.layout.main);
        ScrollView sv = new ScrollView(this);
        DatabaseHandler db = new DatabaseHandler(this);
        TableLayout ll=new TableLayout(this);
        ll.setBackgroundColor(108);
       this.setTitle("Crops Details");
        HorizontalScrollView hsv = new HorizontalScrollView(this);
        LayoutParams layoutParams = new LayoutParams(
        	    LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);

        	layoutParams.setMargins(20, 22, 20, 20);

        	 ll.setLayoutParams(layoutParams); 
        	 ll.setPadding(10, 10, 10, 10);
        	// ll.setBackgroundColor(Color.GREEN);
        	 
        	 int flag =1;

        		String field=new String();
    	    	String crp=new String();
	    // Get the message from the intent
	    Intent intent = getIntent();
	    String message = intent.getStringExtra(ListViewCheckboxesActivity.fields);
	  //  String crp = intent.getStringExtra(ListViewCheckboxesActivity.crops);
	    if(message.contains("@")){
	    String[] parts=message.split("@");
	    
	    Log.d("fields",message+"1here");
		//  Log.d("crops",crp);
	    
field=new String(parts[0]);
crp=new String(parts[1]);

	    }
	    else{
	    	field=message;
	    	  Log.d("fields",message+"111here");
	    	crp=null;
	    }
    ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    TextView tv=new TextView(this);
  	postParameters.add(new BasicNameValuePair("fields",field));
	postParameters.add(new BasicNameValuePair("cropname",crp));
	 String []  header= field.split(",");
	 int fflag=-1,floc=-1;
	 String rk=new String();
    		    String responseforcrop = null;
            	try{
    		 //   responseforcrop = CustomHttpClient.executeHttpPost("http://192.16.12.131/crops.php",postParameters);
            	  //  String rk=responseforcrop.toString();
            		if(crp.contains("#")){
            			Log.d("Before","getCropsByState");
            			Log.d("State",crp.split("#")[0]);
            			 rk=db.getCropsByState(field, crp.split("#")[0],header.length );
            			
            		}
            		else if(crp.trim().equalsIgnoreCase("all")){
            			rk=db.getAllCrops(field, header.length);
            			
            		}
            		else{
            		
            		 rk=db.getCrops(field, crp,header.length );
            		}
if(!(rk.trim().equals("")||rk.trim().equals(null))){
            	    String [] values=new String[]{};
            	Log.d("In ","If");   
            	   // String [] header=new String[]{};
            	   
            	   // String [] header=new String[]{"No.","CropName","Quality","BaseCost/ton(Rs.)","Current Bid Price","Farmer"};
            	    String[] rows=rk.split("</br>");
            		//System.out.println(rows.length);
            		for(int i=0;i<rows.length;i++){
            			
            			if(flag==1){
            				

           	          flag=2;
           	        int ab=db.getCropCount();
           	     
            			}
            			if(flag==2){
            				TableRow tbrow1=new TableRow(this);
            				for(int j=1;j<header.length;j++){
                				
                				TextView tv1=new TextView(this);
                				String str=new String();
                				 if(header[j].equalsIgnoreCase("cropname"))
                		    		 str="Crop Name"; 
                		    	 else if(header[j].equalsIgnoreCase("cropQuality"))
                		    		 str="Crop Quality"; 
                				 //	 else if(country.getName().equalsIgnoreCase("Crop Quantity"))
                	    	//	 str="quantity"; 
                		    	 else if(header[j].equalsIgnoreCase("quantity"))
                		    		 str="Crop Quantity  (In Ton)"; 
                		    	 else if(header[j].equalsIgnoreCase("baseCost"))
                		    		 str="BaseCost/Ton(Rs.)"; 
                		    	 else if(header[j].equalsIgnoreCase("cost"))
                		    		 str="Highest Bid Price(Rs.)"; 
                		    	 else if(header[j].equalsIgnoreCase("fname")){
                		    		 fflag=1;
                		    		 floc=j;
                		    		 str="Farmer";
                		    	 }
                		    	 else if(header[j].equalsIgnoreCase("pkgCost"))
                		    		 str="PackageCost/Ton(Rs.)";
                		    	 else if(header[j].equalsIgnoreCase("state"))
                		    		 str="State";
                				tv1.setHeight(100);
                				tv1.setWidth(100);
                				 tv1.setText(str);
                				 tv1.setTextSize(18);
                				 tv1.setTypeface(null,Typeface.BOLD);
                				 tv1.setPadding(5, 5, 5, 5);
                	             tbrow1.addView(tv1);
                	             flag=0;
                				//System.out.print(values[j]+"  ");
                			
                			}
                			
            				ll.addView(tbrow1);
            				
            				
            				
            			}
            			
            			TableRow tbrow1=new TableRow(this);
            			///System.out.println();
            			//System.out.println(rows[i]+"\n");
            			values=rows[i].split("#");
            			for(int j=1;j<=values.length;j++){
            				
            				if(j==values.length)
            					
                			{	
            					 HashMap<String, String> user = session.getIsFarmer();
           				      
         				        String isFarmer = (user.get(SessionManager.IsFarmer)); 
         				        Log.d("IsFarmer",isFarmer);
            					if(!(isFarmer.trim().equalsIgnoreCase("Yes"))){
                				 // webView1 = (WebView) findViewById(R.id.webView1);
                				webView1= new WebView(this);
                				webView1.setBackgroundColor(Color.BLACK);
                				//webView1.
                				String summary = "<html><head><title>Title of the document</title></head><body><h4><a href=hk"+values[0].toString()+">Bid</a></h4></body></html>";
                			       // String summary = "<html><head><title>Title of the document</title></head><body><h4><a href=\"hrupin://second_activity\">Start Bid</a></h4></body></html>";
                			        webView1.loadData(summary, "text/html", null);
                			        webView1.setWebViewClient(new MyWebViewClient(this));
                			        tbrow1.addView(webView1);
                			}
                			}else if(fflag==1 && floc==j ){
               				 HashMap<String, String> user = session.getIsFarmer();
               			//   tbrow1.removeAllViews();
         				   
                				 // webView1 = (WebView) findViewById(R.id.webView1);
                				webView2= new WebView(this);
                				webView2.setBackgroundColor(Color.BLACK);
                				//webView1.
                				String summary = "<html><head><title>Title of the document</title></head><body><h4><a href=hk"+values[0].toString()+">"+values[j].toString()+"</a></h4></body></html>";
                			       // String summary = "<html><head><title>Title of the document</title></head><body><h4><a href=\"hrupin://second_activity\">Start Bid</a></h4></body></html>";
                			        webView2.loadData(summary, "text/html", null);
                			        webView2.setWebViewClient(new MyWebviewFarmer(this));
                			        tbrow1.addView(webView2);
               			}
            				else{
            				TextView tv1=new TextView(this);
            				tv1.setHeight(50);
            				tv1.setWidth(100);
            				 tv1.setText(values[j]);
            				 tv1.setTextSize(15);
            				 tv1.setPadding(5, 5, 5, 5);
            	             tbrow1.addView(tv1);
            				//System.out.print(values[j]+"  ");
            				}
            			}
            			
            			ll.addView(tbrow1);
            		}
            	    
            	
            	    
            		hsv.addView(ll);
                    sv.addView(hsv);
                    setContentView(sv); 
            	    
            	    
            	    
    	    	
}else{
	tv.setText("No Crop Available");
	Log.d("In ","else");   
	 setContentView(tv);
}
    	  
    	} catch (Exception e) {
    		tv.setText("In catch"+e.toString());
    		 setContentView(tv);
    	}

	    // Create the text view
    	
	  
    	
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_display_message, menu);
		return true;
	}

	//@Override
	

}
